﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UCodeFirstApplicationEventHandler.cs" company="CodePlex">
//   The MIT License
//   Copyright (c) 2013 Julien Blin
//   
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//   
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//   
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace UCodeFirst
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Threading.Tasks;
    using System.Web.Hosting;

    using Umbraco.Core;
    using Umbraco.Core.Logging;

    /// <summary>
    /// The uCodeFirst <see cref="IApplicationEventHandler"/> that starts the synchronization process.
    /// </summary>
    public class UCodeFirstApplicationEventHandler : IApplicationEventHandler
    {
        /// <summary>
        /// The assemblies hash store key.
        /// </summary>
        private const string AssembliesHashStoreKey = @"AssembliesHash";

        /// <summary>
        /// List of managers.
        /// </summary>
        private IList<UCodeFirstManagerBase> managers;

        /// <summary>
        /// Gets the list of managers.
        /// </summary>
        public IList<UCodeFirstManagerBase> Managers
        {
            get
            {
                return this.managers
                       ?? (this.managers =
                           TypesScanner.GetClassesInBinThatAreAssignableFrom<UCodeFirstManagerBase>()
                                       .Select(x =>
                                           {
                                               var manager = x.CreateInstance<UCodeFirstManagerBase>();
                                               manager.UCodeFirstApplicationEventHandler = this;
                                               return manager;
                                           })
                                       .OrderBy(x => x.Priority)
                                       .ToList());
            }
        }

        /// <summary>
        /// On application initialized - no-op.
        /// </summary>
        /// <param name="httpApplication">
        /// The http application.
        /// </param>
        /// <param name="applicationContext">
        /// The application context.
        /// </param>
        public void OnApplicationInitialized(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
        {
            // No-op
        }

        /// <summary>
        /// On application starting - no-op.
        /// </summary>
        /// <param name="httpApplication">
        /// The http application.
        /// </param>
        /// <param name="applicationContext">
        /// The application context.
        /// </param>
        public void OnApplicationStarting(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
        {
            // No-op
        }

        /// <summary>
        /// On application started.
        /// </summary>
        /// <param name="httpApplication">
        /// The http application.
        /// </param>
        /// <param name="applicationContext">
        /// The application context.
        /// </param>
        public void OnApplicationStarted(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
        {
            try
            {
                var stopWatch = Stopwatch.StartNew();
                LogHelper.Debug<UCodeFirstApplicationEventHandler>(Resources.Starting);
                if (!applicationContext.IsConfigured)
                {
                    LogHelper.Info<UCodeFirstApplicationEventHandler>(Resources.UmbracoNotConfigured);
                    return;
                }

                LogHelper.Debug<UCodeFirstApplicationEventHandler>(Resources.FoundNManagers.InvariantFormat(this.Managers.Count()));

                this.Managers.ForEach(
                    x =>
                    {
                        LogHelper.Debug<UCodeFirstApplicationEventHandler>(Resources.BeforeSynchronizationManager.InvariantFormat(x));
                        x.BeforeSynchronization(httpApplication, applicationContext);
                    });

                var synchronizationHappened = false;
                if (UCodeFirstConfig.SynchronizationMode != SynchronizationMode.None)
                {
                    var currentHash = this.ComputeAssembliesHash();
                    var storedHash = UCodeFirstData.GetValue<UCodeFirstApplicationEventHandler>(AssembliesHashStoreKey);

                    if (!currentHash.Equals(storedHash, StringComparison.InvariantCulture)
                        || (UCodeFirstConfig.SynchronizationMode == SynchronizationMode.Force))
                    {
                        LogHelper.Info<UCodeFirstApplicationEventHandler>(Resources.SynchronizingDatabase);
                        this.managers.ForEach(
                            x =>
                            {
                                LogHelper.Debug<UCodeFirstApplicationEventHandler>(Resources.SynchronizeManager.InvariantFormat(x));
                                x.Synchronize(httpApplication, applicationContext);
                            });
                        synchronizationHappened = true;
                    }

                    if (!currentHash.Equals(storedHash, StringComparison.InvariantCulture))
                    {
                        UCodeFirstData.SetValue<UCodeFirstApplicationEventHandler>(AssembliesHashStoreKey, currentHash);
                    }
                }

                this.managers.Reverse().ForEach(
                    x =>
                    {
                        LogHelper.Debug<UCodeFirstApplicationEventHandler>(Resources.AfterSynchronizationManager.InvariantFormat(x));
                        x.AfterSynchronization(httpApplication, applicationContext, synchronizationHappened);
                    });

                stopWatch.Stop();
                LogHelper.Info<UCodeFirstApplicationEventHandler>(Resources.EndedSuccessFullyIn.InvariantFormat(stopWatch.ElapsedMilliseconds));
            }
            catch (Exception ex)
            {
                LogHelper.Error<UCodeFirstApplicationEventHandler>(Resources.UnableToFinishUCodeFirstExceution, ex);
                throw;
            }
        }

        /// <summary>
        /// Compute a hash for all the assemblies in the ~/bin directory.
        /// </summary>
        /// <returns>
        /// The computed hash.
        /// </returns>
        private string ComputeAssembliesHash()
        {
            var fileHashes = new Dictionary<string, byte[]>();
            var path = HostingEnvironment.MapPath("~/bin");
            Debug.Assert(path != null, "path != null");
            Parallel.ForEach(
                TypesScanner.AssembliesInBin.Value.Select(x => x.Location),
                assemblyPath =>
                {
                    using (var stream = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        fileHashes[assemblyPath] = MD5.Create().ComputeHash(stream);
                    }
                });

            return string.Join(string.Empty, fileHashes.Keys.OrderBy(x => x).Select(x => BitConverter.ToString(fileHashes[x]))).GetHashCode().ToString(CultureInfo.InvariantCulture);
        }
    }
}
